<?php
/*
php zip压缩文件夹下面的所有文件
*/
class PHPZip
{
  /**
   * 添加文件和子目录的文件到zip文件
   * @param string $folder
   * @param ZipArchive $zipFile
   * @param int $exclusiveLength Number of text to be exclusived from the file path.
   */
  private static function folderToZip($folder, &$zipFile, $exclusiveLength) {
    $handle = opendir($folder);
    while (false !== $f = readdir($handle)) {
      if ($f != '.' && $f != '..') {
        $filePath = "$folder/$f";
        // Remove prefix from file path before add to zip.
        $localPath = substr($filePath, $exclusiveLength);
        if (is_file($filePath)) {
          $zipFile->addFile($filePath, $localPath);
        } elseif (is_dir($filePath)) {
          // 添加子文件夹
          $zipFile->addEmptyDir($localPath);
          self::folderToZip($filePath, $zipFile, $exclusiveLength);
        }
      }
    }
    closedir($handle);
  }
 
  /**
   * Zip a folder (include itself).
   * Usage:
   *   HZip::zipDir('/path/to/sourceDir', '/path/to/out.zip');
   *
   * @param string $sourcePath Path of directory to be zip.
   * @param string $outZipPath Path of output zip file.
   */
  public static function zipDir($sourcePath, $outZipPath, $download = true)
  {
  	$outZipPath = iconv( 'UTF-8', 'gb2312', $outZipPath);
    $pathInfo = pathInfo($sourcePath);
    $parentPath = $pathInfo['dirname'];
    $dirName = $pathInfo['basename'];
    $sourcePath=$parentPath.'/'.$dirName;//防止传递'folder' 文件夹产生bug
    $z = new ZipArchive();
    if($z->open($outZipPath, ZIPARCHIVE::CREATE)!==true)//建立zip文件
    {
    	exit ( '无法打开文件，或者文件创建失败' );
    }
    $z->addEmptyDir($dirName);//建立文件夹
    self::folderToZip($sourcePath, $z, strlen("$parentPath/"));
    $z->close();
    if ($download){
    	self::downLoad($outZipPath,'drleawell');
    	@unlink($outZipPath);
	    if ($handle = opendir($sourcePath)) {
		     while (false !== ($file = readdir($handle))){
			     if ($file != '.' && $file != '..') {
			        @unlink("$sourcePath/$file");
			      }
			    }
		}
    }else{
    	
    }
  }
  
  private static function downLoad($filepath,$filename)
  {
  	$filename = urldecode($filename.basename($filepath));
  	header ( "Cache-Control: max-age=0" );
  	header ( "Content-Description: File Transfer" );
  	header ( 'Content-disposition: attachment; filename=' . $filename); // 文件名
  	header ( "Content-Type: application/zip" ); // zip格式的
  	header ( "Content-Transfer-Encoding: binary" ); // 告诉浏览器，这是二进制文件
  	header ( 'Content-Length: ' . filesize ( $filepath ) ); // 告诉浏览器，文件大小
  	@readfile ( $filepath );//输出文件;
  }
}

?>